package com.mq.dialogdemo.dialogfragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;

import com.mq.dialogdemo.R;

/**
 * Created by Lenovo on 2017/6/7.
 */

public class MyDialogFragment extends DialogFragment {

    public interface MyDialogListener {
        void onDialogClick(String content, int type);
    }

    private MyDialogListener myDialogListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            myDialogListener = (MyDialogListener) context;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(context.toString()
                    + " must implement MyDialogListener");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
//        return super.onCreateDialog(savedInstanceState);

        View view = View.inflate(getContext(), R.layout.dialog_login, null);

        final EditText etUser = (EditText) view.findViewById(R.id.et_user);
        final EditText etPassword = (EditText) view.findViewById(R.id.et_password);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setTitle("MyDialogFragment")
                .setView(view)
                .setPositiveButton("user", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myDialogListener.onDialogClick(etUser.getText().toString(), 1);
                    }
                })
                .setNegativeButton("password", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myDialogListener.onDialogClick(etPassword.getText().toString(), 2);
                    }
                });

        AlertDialog alertDialog = builder.create();

        alertDialog.setCanceledOnTouchOutside(false);

        return alertDialog;
    }
}
